<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
<title>出入库信息管理</title>
<meta name="decorator" content="default" />
<meta http-equiv="Expires" CONTENT="0">
<meta http-equiv="Cache-Control" CONTENT="no-cache">
<meta http-equiv="Pragma" CONTENT="no-cache">
<link href="${ctxStatic}/bootstrap-editable/css/bootstrap-editable.css" rel="stylesheet" />
<link href="${ctxStatic}/bootstrap-table/bootstrap-table.min.css" rel="stylesheet" />
<script src="${ctxStatic}/bootstrap-editable/js/bootstrap-editable.js"></script>
<script src="${ctxStatic}/bootstrap-table/bootstrap-table.js"></script>
<script src="${ctxStatic}/bootstrap-table/locale/bootstrap-table-zh-CN.js"></script>
<script src="${ctxStatic}/bootstrap-table/extensions/editable/bootstrap-table-editable.js"></script>
<script src="${ctxStatic}/common/format/formatOrderData.js"></script>
<script src="${ctxStatic}/common/change/change.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$('#tab').bootstrapTable({
			url: "${ctx}/order_detail/bsVaccineOrderDetail/getOrderDetailMap",
	    	toolbar: "#toolbar",
	    	clickToSelect :true,
	    	uniqueId: "id",      //每一行的唯一标识，一般为主键列 
	    	queryParams: function (param) {
	            return {id :'${bsVaccineOrder.id}'};
	        } ,
			columns : [ {
				field : "选择",
				checkbox : true
			}, {
				field : 'reOrderId',
				title : 'reOrderId',
				visible : false
			}, {
				field : 'reId',
				title : 'reId',
				visible : false
			}, {
				field : 'index',
				title : 'index',
				visible : false
			}, {
				field : 'id',
				title : 'id',
				visible : false
			}, {
				field : 'batchnoId',
				title : 'batchnoId',
				visible : false
			}, {
				field: 'productId',
	            title: 'productId',
	            visible: false
	        }, {
				field : 'name',
				title : '疫苗名称/注射器类型'
			}, {
				field : 'sort',
				title : '属性',
				formatter : formatSort
			}, {
				field : 'companyName',
				title : '生产企业'
			}, {
	            field: 'companyCode',
	            title: '生产企业编码',
	            visible:false 
	        }, {
				field : 'batchno',
				title : '批号',
	            formatter:formatBatchno
			}, {
				field : 'spec',
				title : '规格(剂/支或粒)',
	            formatter:formatSpec
			}, {
				field : 'dose',
				title : '剂量'
			}, {
				field : 'vaccExpDate',
				title : '有效日期',
				formatter : formatDate
			}, {
				field : 'storenum',
				title : '库存'
			}, {
				field : 'storenumF',
				title : '可用库存',
				formatter : formatStorenumF
			}, {
				field : 'num',
				title : '退回数量',
	            width:'150px',
				editable : {
					type : 'text',
					title : '退回数量',
					emptytext : '0',
	                inputclass:'input-mini',
	                mode:'inline',
					validate : function(v) {
						var num = parseInt(v)
						var num_reg = /^\+?[1-9][0-9]*$/;
						if (!num_reg.test(v)) {
							return '退回数量不合法';
						}
					}
				}
			}, {
				field: 'orignprice',
	            title: '成本价格'
			}, { 
				field : 'sellprice',
				title : '出售价格'
			}]
		});
		
		$("#inputForm").validate({
			submitHandler : function(form) {
					postOrderDetil(form);
			},
			ignore : ":hidden",
			errorContainer : "#messageBox",
			errorPlacement : function(error, element) {
				$("#messageBox").text("输入有误，请先更正。");
				if (element.is(":checkbox")
						|| element.is(":radio")
						|| element.parent().is(
								".input-append")) {
					error.appendTo(element.parent()
							.parent());
				} else {
					error.insertAfter(element);
				}
			}
		});
		$("#BtnNumShow").click(function(){
			var val2 = $('input:radio[name="cType"]:checked').val();
			var companyCode = "";
			var checked = $("input:radio[name='company']:checked").val();
			if(checked == '2'){
				companyCode = $("#receiveorgcode2").val();
			}
			if (!val2) {
				val2 = '';
				layer.msg("请先选择疫苗类型！");
			}
			var url = "${ctx}/vaccinate/bsProduct/getList?cType="+val2+"&companyCode="+companyCode;
			layer.open({
				type : 2,
				title : '库存列表',
				shadeClose : true,
				shade : 0.8,
				area : [screen.availWidth * 0.7 + 'px', screen.availHeight * 0.6 + 'px' ],
				content : url
			});
		});
		$("#BtnDelete").click(function(){
			debugger;
			var deleteData = $('#deleteData').val();
			var ids = $.map($('#tab').bootstrapTable('getSelections'), function (row) {
				if (row.id){
					deleteData = deleteData+row.id+","
					return row.id;
				}else{
					return row.index;
				}
            });
			$('#tab').bootstrapTable('remove', {
                field: 'id',
                values: ids
            });
			$('#tab').bootstrapTable('remove', {
                field: 'index',
                values: ids
            });
			$('#deleteData').val(deleteData);
		});
		
		$(".trantype").click(function(){
			var str=$(this).val();
			if(str=='3'){
				$(".traninput")[0].readOnly=false;
			}else{
				$(".traninput")[0].readOnly=true;
			}
		})
		
		$(".reftype").click(function(){
			var str=$(this).val();
			if(str=='3'){
				$(".refinput")[0].readOnly=false;
			}else{
				$(".refinput")[0].readOnly=true;
			}
		});
		$(".company").click(function(){
			var str = $(this).val();
			if (str == '1') {
				if($("#receiveorgcode").val().length<6){
					$("#receiveorgcode1Id").val("");
					$("#receiveorgcode1Name").val("");
				}
				$("#company_treeselect").show();
				$("#company_select").hide();
			} else {
				$("#company_treeselect").hide();
				$("#company_select").show();
			}
		});
		initVaccCompanyName(bsVaccineOrder.receiveorgcode,bsVaccineOrder.receiveorgName);
	});
	var bsVaccineOrder = JSON.parse('${fns:toJson(bsVaccineOrder)}');
	function transportChoose(value){
		$($('input:radio[name=transportation]').eq(value)).prop('checked',false);
		if(value=='3'){
			$(".traninput")[0].readOnly=false;
		}else{
			$(".traninput").val("");
			$(".traninput")[0].readOnly=true;
		}
	}
	function layerDiv(obj) {
		var tr = obj;
		tr.sellprice = tr.orignprice;
		$('#tab').bootstrapTable('getData', false);
		var rows = $('#tab').bootstrapTable('getData');
		for(var i = 0 in rows){
			if(obj.batchnoId == rows[i].batchnoId){
				layer.msg("该批号已在出入库单中，请勿多次选择");
				return;
			}
		}
		$('#tab').bootstrapTable('append', tr);
	}
	function formatStorenumF(data, row, index){
		var storenumF = row.storenumF;
		var storenum = row.storenum;
		return storenum-storenumF;
	}
	function formatSort(data, row, index) {
		if (data == "1") {
			return "第一类";
		} else if (data == "2") {
			return "第二类";
		} else {
			return data;
		}
	};
	function formatDate(date) {
		if (!date) {
			return "";
		}
		var d = new Date(date), month = '' + (d.getMonth() + 1), day = ''
				+ d.getDate(), year = d.getFullYear();
		if (month.length < 2)
			month = '0' + month;
		if (day.length < 2)
			day = '0' + day;
		return [ year, month, day ].join('-');
	}
	function postOrderDetil(form) {//表单保存时  将此方法中的数据尽行保存
		//校验疫苗运输方式
		debugger;
		var val = $('input:radio[name="transportation"]:checked').val();
		if (!val) {
			$("#t-msg").find("font").text("*必填信息");
			return;
		}
		var val1 = $('input:radio[name="refrigeratetype"]:checked').val();
		if (!val1) {
			$("#r-msg").find("font").text("*必填信息");
			return;
		}
		//校验疫苗疫苗类型
		var val2 = $('input:radio[name="cType"]:checked').val();
		if (!val2) {
			$(".type-msg").find("font").text("必填信息");
			return;
		}
		//校验生产厂商编码
		var val3 = $('input:radio[name="company"]:checked').val();
		if (val3 =='1'){
			var receiveorgcode1 = $("#receiveorgcode1Id").val();
			var receiveorgName1 = $("#receiveorgcode1Name").val();
			if (!receiveorgcode1) {
				layer.msg("未选择收货单位！");
				return;
			}
			$("#receiveorgcode").val(receiveorgcode1);
			$("#receiveorgName").val(receiveorgName1);
		}else{
			var receiveorgcode2 = $("#receiveorgcode2").val();
			if (!receiveorgcode2) {
				layer.msg("未选择收货单位！");
				return;
			}
			var receiveorgName2 = $("#receiveorgcode2").find("option:selected").text();
			$("#receiveorgcode").val(receiveorgcode2);
			$("#receiveorgName").val(receiveorgName2);
		}
		var rows = $('#tab').bootstrapTable('getData');
		var rowIndex = rows.length;
		var result = false;
		if (rowIndex > 0) {
			for(var i = 0;i<rowIndex;i++ ){
				var num = parseInt(rows[i].num);
				var storenum = parseInt(rows[i].storenum);
				var storenumF = parseInt(rows[i].storenumF);
				var storenumK = storenum -storenumF;
				var reSum = parseInt(rows[i].reSum);
				var num_reg = /^\+?[1-9][0-9]*$/;
				if ( rows[i].sort != val2){
					layer.msg("疫苗种类不符合，请确认疫苗种类");
					return;
				}if (!num_reg.test(rows[i].num)||num < 0 || num > storenum || num > reSum || num > storenumK) {
					layer.msg("出库数量不合法！请检查是否大于库存,或大于原订单数量")
					return;
				}if (val3 =='2'){
					debugger;
					if(rows[i].companyCode != receiveorgcode2){
						layer.msg("疫苗生产企业与所选收货单位不一致！");
						return;
					}
				}
			}
			$("#tableData").val(JSON.stringify(rows)+"");
			layer.confirm('确定保存？', {
				icon: 3, title:'提示',
				btn : [ '保存', '取消' ]
			//按钮
			}, function() {
				layer.load(2);
				loading('正在提交，请稍等...');
				form.submit();
			});
		}else{
			layer.confirm('没有添加数据,确定保存？', {icon: 3, title:'提示'}, {
				btn : [ '保存', '取消' ]
			//按钮
			}, function() {
				layer.load(2);
				loading('正在提交，请稍等...');
				form.submit();
			});
		}
	}
	//注射器规格字典表
	var specDic = jQuery.parseJSON('${fns:getDictListJson("syringe_spec")}');
</script>
<style type="text/css">
input[type="checkbox"] {
	display: block;
}
.input-xlarge-search {
	width: 266px;
}
</style>
</head>
<body>
	<ul class="nav nav-tabs">
		<%-- <li class="active"><a href="${ctx}/order/bsVaccineOrder/form?id=${bsVaccineOrder.id}">疫苗退回</a></li> --%>
		<li class="active"><a href="#">疫苗退回</a></li>
	</ul>
	<br />
	<form:form id="inputForm" modelAttribute="bsVaccineOrder" action="${ctx}/order/bsVaccineOrder/update" method="post" class="form-horizontal">
		<form:hidden path="id"/>
		<input id="deleteData" type="hidden" name="deleteData">
		<input id="receiveorgcode" type="hidden" name="receiveorgcode">
		<input id="receiveorgName" type="hidden" name="receiveorgName">
		<input id="supplyorgCode" type="hidden" name="supplyorgCode" value="${bsVaccineOrder.supplyorgCode}"><!-- 供货单位编码  -->
		<input id="orderType" type="hidden" name="orderType" value="${bsVaccineOrder.orderType}">
		<input id="orderStatus" type="hidden" name="orderStatus" value="${bsVaccineOrder.orderStatus}">
		<input id="tempStatus" type="hidden" name="tempStatus" value="${bsVaccineOrder.tempStatus}">
		<input id="createcode" type="hidden" name="createcode" value="${bsVaccineOrder.createcode}">
		<input id="createorgName" type="hidden" name="createorgName" value="${bsVaccineOrder.createorgName}">
		<sys:message content="${message}" />
		<div class="row-fluid">
			<div class="control-group span6 minWidth secondChild">
				<label class="control-label">订单号：</label>
				<div class="controls">
					<form:input path="orderNo" htmlEscape="false" maxlength="50"
						readonly="true" class="span6" />
				</div>
			</div>
			<div class="control-group span6 minWidth">
				<label class="control-label">订单状态：</label>
				<div class="controls">
					<input name="orderStatusOld" type="text"  maxlength="20" class="span6 required" readonly
						value="${fns:getDictLabels(orderStatusOld, 'bs_order_status', '')}"/>
				</div>
			</div>
		</div>
		<div class="row-fluid">
			<div class="control-group span6 minWidth">
				<label class="control-label"><span class="help-inline"><font color="red">*</font> </span> 出库日期：</label>
				<div class="controls">
					<input name="outboundDate" type="text" readonly="readonly"
						maxlength="20" class="span6 Wdate required"
						value="<fmt:formatDate value="${bsVaccineOrder.outboundDate}" pattern="yyyy-MM-dd"/>"
						onclick="WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:true});" />
				</div>
			</div>
			<div class="control-group span6 minWidth secondChild">
				<label class="control-label"><span class="help-inline"><font color="red">*</font> </span> 类型：</label>
				<div class="controls">
					<form:select path="orderType" readonly="true" disabled="true"
						class="span6 required ordertype">
						<form:options items="${fns:getDictList('bs_order_ordertype')}"
							itemLabel="label" itemValue="value" htmlEscape="false" />
					</form:select>
				</div>
			</div>
		</div>
		<div class="row-fluid tools">
			<div class="control-group span6 minWidth">
				<label class="control-label"><span class="help-inline"><font color="red">*</font> </span> 供货单位：</label>
				<div class="controls">
					<form:input path="supplyorgName" readonly="true" htmlEscape="false"
						maxlength="255" class="span6 required" />
					
				</div>
			</div>
			<div class="control-group span6 minWidth secondChild">
				<label class="control-label"><span class="help-inline"><font color="red">*</font> </span> 供货单位经手人：</label>
				<div class="controls">
					<form:input path="consignorName" htmlEscape="false" maxlength="50"
						class="span6 required" />
				</div>
			</div>
		</div>
		<div class="row-fluid tools">
			<div class="control-group span6 minWidth">
				<label class="control-label"><span class="help-inline"><font color="red">*</font> </span> 收货单位：</label>
				<div class="controls">
					<span id = "company_treeselect" <c:if test="${fn:length(bsVaccineOrder.receiveorgcode) < 6}"> style = "display:none;" </c:if>>
					<sys:treeselect2 id="receiveorgcode1" name="receiveorgcode1" value="${bsVaccineOrder.receiveorgcode}" labelName="receiveorgName1" labelValue="${bsVaccineOrder.receiveorgName}"
				        notAllowSelectParent ="true" notAllowSelectRoot = "true" title="单位" url="/sys/office/treeData2?areaType=3" cssClass="input-xlarge-search" layer = "true"/>
					</span>
					<span id = "company_select" <c:if test="${fn:length(bsVaccineOrder.receiveorgcode) >= 6}"> style = "display:none;" </c:if>>
						<select id="receiveorgcode2" name="receiveorgcode2" class="span6 vaccCompanyName">
							<option value="" label="--请选择--"/> 
						</select>
					</span>
					<span><input id = "company1" type="radio" name="company" value="1" class = "company" <c:if test="${fn:length(bsVaccineOrder.receiveorgcode) >= 6}"> checked</c:if>>上级疾控</span>
					<span><input id = "company2" type="radio" name="company" value="2" class = "company" <c:if test="${fn:length(bsVaccineOrder.receiveorgcode) < 6}"> checked</c:if>>生产厂商</span>
				</div>
			</div>
			<div class="control-group span6 minWidth secondChild">
				<label class="control-label">收货单位经手人：</label>
				<div class="controls">
					<form:input path="consigneeName" htmlEscape="false" maxlength="50"
						class="span6" />
				</div>
			</div>
		</div>
		<div class="row-fluid  tools">
			<div class="control-group span6 minWidth ">
				<label class="control-label"><span class="help-inline" id="t-msg"><font color="red">*</font> </span> 疫苗运输工具：</label>
				<div class="controls">
					<form:radiobuttons path="transportation"
						items="${fns:getDictList('bs_order_transportation')}"
						itemLabel="label" itemValue="value" class="required trantype" />
					<form:input path="otherTransportation" readonly="false"
						htmlEscape="false" maxlength="50" class="input-mini traninput" />
					
				</div>
			</div>
			<div class="control-group span6 minWidth secondChild">
				<label class="control-label"><span class="help-inline" id="r-msg"><font color="red">*</font></span> 疫苗冷藏方式：</label>
				<div class="controls">
					<form:radiobuttons path="refrigeratetype"
						items="${fns:getDictList('bs_order_refrigeratetype')}"
						itemLabel="label" itemValue="value" class="required reftype" />
					<form:input path="otherRefrigeratetype" readonly="false"
						htmlEscape="false" maxlength="50" class="input-mini refinput" />
				</div>
			</div>
		</div>
		<%-- <div class="row-fluid">
			<div class="control-group span6">
				<label class="control-label"><span class="help-inline"><font color="red">*</font></span> 疫苗类型：</label>
				<div class="controls">
					<form:radiobuttons path="cType" items="${fns:getDictList('bs_vaccine_type')}"
						itemLabel="label" itemValue="value" class="required" />
					<span class="help-inline type-msg error"><font color="red"></font></span>
				</div>
			</div>
		</div> --%>
		<div class="row-fluid">
			<div class="control-group span6">
				<label class="control-label"><span class="help-inline"><font color="red">*</font></span> 疫苗类型：</label>
				<div class="controls">
					<form:radiobuttons path="cType" items="${fns:getDictList('bs_vaccine_type')}"
						itemLabel="label" itemValue="value" class="required" />
					<span class="help-inline type-msg error"><font color="red"></font></span>
				</div>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">备注信息：</label>
			<div class="controls">
				<form:textarea path="remarks" htmlEscape="false" rows="3"
					style="width: 78%;resize: vertical;" maxlength="100"
					class="input-xlarge" placeholder="最多输入100个字" />
			</div>
		</div>

		<div id="toolbar">
			<button type="button" id="BtnNumShow" class="btn btn-primary">库存量查询</button>
			<button type="button" id = "BtnDelete" class="btn btn-primary">删除</button>
		</div>

		<div class="control-group">
			<input id="tableData" type="hidden" name="tableData">
			<table id="tab" class="table table-bordered table-condensed">
			</table>
		</div>

		<div class="form-actions">
			<shiro:hasPermission name="order:bsVaccineOrder:edit">
				<input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存" />
			</shiro:hasPermission>
			<input id="btnCancel" class="btn btn-primary" type="button"
				value="返 回" onclick="history.go(-1)" />
		</div>
	</form:form>
</body>
</html>